﻿using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows.Forms;
using Devv.Threeter.Properties;
using Devv.Threeter.Twitter;
using TweetSharp;

namespace Devv.Threeter
{
	public partial class FormAccounts : Form
	{
		#region Properties

		private OAuthRequestToken requestToken;
		private OAuthAccessToken accessToken;

		#endregion

		#region Loading
		
		public FormAccounts()
		{
			InitializeComponent();
		}

		private void FormAccounts_Load(Object sender, EventArgs e)
		{
			gridAccounts.AutoGenerateColumns = false;
			gridAccounts.DataSource = Program.CurrentAccounts;
		}

		private void FormAccounts_FormClosing(object sender, FormClosingEventArgs e)
		{
			Program.CurrentAccounts.Save();
			Program.FormPostInstance.RefreshMenuAccounts();
		}

		private void FormAccounts_KeyDown(Object sender, KeyEventArgs e)
		{
			if (e.KeyData == Keys.Escape)
			{
				DialogResult = DialogResult.Abort;
			}
		}

		#endregion

		#region Add account

		private void butAuthorize_Click(Object sender, EventArgs e)
		{
			requestToken = TwitterManager.Service.GetRequestToken();

			Uri uri = TwitterManager.Service.GetAuthorizationUri(requestToken);
			Process.Start(uri.ToString());

			butAuthorize.Visible = false;
			lblAuthorize.Visible = false;

			butConfirm.Visible = true;
			lblPIN.Visible = true;
			txtPIN.Visible = true;
		}

		private void butConfirm_Click(Object sender, EventArgs e)
		{
			if (txtPIN.Text.Length < 3)
			{
				MessageBox.Show(Messages.ErrorEnterPIN, Messages.Login, MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}

			Cursor = Cursors.WaitCursor;

			txtPIN.Text = txtPIN.Text.Trim();

			workerAddAccount.RunWorkerAsync(TwitterManager.Service.GetAccessToken(requestToken, txtPIN.Text));
		}

		private void workerAddAccount_DoWork(Object sender, DoWorkEventArgs e)
		{
			accessToken = e.Argument as OAuthAccessToken;

			if (accessToken == null)
			{
				e.Result = null;
				return;
			}

			try
			{
				TwitterManager.Service.AuthenticateWith(accessToken.Token, accessToken.TokenSecret);
				e.Result = TwitterManager.Service.GetUserProfile();
			}
			catch
			{
				e.Result = null;
			}
		}

		private void workerAddAccount_RunWorkerCompleted(Object sender, RunWorkerCompletedEventArgs e)
		{
			Cursor = Cursors.Default;

			butConfirm.Visible = false;
			lblPIN.Visible = false;
			txtPIN.Visible = false;

			butAuthorize.Visible = true;
			lblAuthorize.Visible = true;

			if (e.Result != null)
			{
				TwitterUser tu = e.Result as TwitterUser;
				Boolean found = false;

				foreach (Account login in Program.CurrentAccounts)
				{
					if (login.Username.ToLower() == tu.ScreenName.ToLower())
					{
						login.Token = accessToken.Token;
						login.Secret = accessToken.TokenSecret;

						found = true;
						break;
					}
				}

				if (!found)
				{
					TwitterManager.LoggedAccount = new Account(tu.ScreenName, accessToken.Token, accessToken.TokenSecret);
					Program.CurrentAccounts.Add(TwitterManager.LoggedAccount);
				}

				Settings.Default.Username = TwitterManager.LoggedAccount.Username;
				Settings.Default.Save();
			}
			else
			{
				MessageBox.Show(Messages.ErrorInvalidLogin, Messages.Login, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}

			txtPIN.Text = String.Empty;
		}

		#endregion

		#region Grid methods

		private void gridAccounts_CellMouseMove(Object sender, DataGridViewCellMouseEventArgs e)
		{
			if (e.ColumnIndex < 0 || e.RowIndex < 0)
			{
				return;
			}

			if (gridAccounts.Columns[e.ColumnIndex].CellType == typeof(DataGridViewImageCell))
			{
				Cursor = Cursors.Hand;
			}
			else
			{
				Cursor = Cursors.Default;
			}
		}

		private void gridAccounts_CellMouseLeave(Object sender, DataGridViewCellEventArgs e)
		{
			Cursor = Cursors.Default;
		}

		private void gridAccounts_CellMouseDown(Object sender, DataGridViewCellMouseEventArgs e)
		{
			if (e.ColumnIndex < 0 || e.RowIndex < 0)
			{
				return;
			}

			if (gridAccounts.Columns[e.ColumnIndex].Name == "colDefault")
			{
				for (Int32 i = 0; i < gridAccounts.Rows.Count; i++)
				{
					gridAccounts["colDefault", e.RowIndex].Value = false;
				}

				gridAccounts["colDefault", e.RowIndex].Value = true;

				String username = gridAccounts["colUsername", e.RowIndex].Value.ToString();
				Settings.Default.Username = username;
			}
			else if (gridAccounts.Columns[e.ColumnIndex].Name == "colDelete")
			{
				String username = gridAccounts["colUsername", e.RowIndex].Value.ToString();
				Program.CurrentAccounts.Remove(username);
			}
		}

		private void gridAccounts_CellValidating(Object sender, DataGridViewCellValidatingEventArgs e)
		{
			if (e.ColumnIndex < 0 || e.RowIndex < 0)
			{
				return;
			}

			if (e.FormattedValue == null || String.IsNullOrEmpty(e.FormattedValue.ToString()))
			{
				gridAccounts.Rows[e.RowIndex].ErrorText = Messages.ErrorAccountCellEmpty;
				e.Cancel = true;
			}
			else
			{
				gridAccounts.Rows[e.RowIndex].ErrorText = String.Empty;
			}
		}

		#endregion
	}
}